<template>
    <view class="main">
        <view class="logoBox">
            <img :src="logoPath" alt="">
        </view>
        <view class="btnBox">
            <button class="submitBtn" @click="handleGetUserInfo">微信授权登录</button>
        </view>
        <view class="fontBox">
            <span>登录既表示同意<font>《易搬家用户协议和隐私政策》</font></span>
        </view>
    </view>
</template>

<script>
    import {
        login
    } from '@/service/login.js'
    import {
        getOpenid
    } from '@/service/getOpenid.js'
    import {
        checkLogin,
        setStorage,
        getStorage,
        getTime,
        getDomain
    } from '@/utils/utils.js'
    export default {
        data() {
            return {
                logoPath: getDomain() + '/member/logo.png',
                pid: 0
            }
        },
        methods: {
            handleGetUserInfo() {
                this.onGetUserInfo().catch(error => {
                    console.log(error)
                })
            },
            // 微信登录
            async onGetUserInfo() {
                const {
                    options
                } = this;
                // 获取用户信息
                const userInfo = await this.onwechatInfos();
                // 获取code
                const code = await this.onwechatcodes();
                // 获取用户openid
                const openData = await getOpenid({
                    'code': code,
                    'userInfo': JSON.stringify(userInfo),
                    'timestamp': getTime(),
                    'pid': this.pid,
                });
                setStorage('userInfo', userInfo);
                setStorage('openId', openData.data.openid);
                setStorage('sessionKey', openData.data.session_key);
                setStorage('x-token', openData.data.token);
                if (checkLogin()) {
                    uni.switchTab({
                        url: `../index/index`
                    })
                }
            },
            // 获取用户信息
            async onwechatInfos() {
                return new Promise((resolve, reject) => {
                    // 判断应用的 API，回调，参数，组件等是否在当前版本可用。
                    if (!uni.canIUse('getUserProfile')) return null;
                    uni.getUserProfile({
                        lang: 'zh_CN',
                        desc: '获取用户相关信息',
                        success: res => {
                            uni.showToast({
                                title: '登录成功',
                                icon: 'success',
                                duration: 2000
                            })
                            // console.log('用户同意了授权', res);
                            this.formData = res.userInfo;
                            return resolve(res.userInfo);
                        },
                        fail: err => {
                            uni.showToast({
                                title: '您拒绝了授权',
                                icon: 'error',
                                duration: 2000
                            });
                            // uni.reLaunch({
                            //     url:'../index/index'
                            // })
                            return reject(err);
                        },
                    });
                })
            },
            // 获取code
            async onwechatcodes() {
                // 获取服务供应商
                const [providerErr, providerData] = await uni.getProvider({
                    service: 'oauth'
                });
                if (providerErr) return uni.showToast({
                    title: '没有获取到服务商',
                    icon: "none"
                })
                const provider = providerData.provider;
                if (provider.includes('weixin')) {
                    const options = {
                        provider: provider[0] //'weixin'
                    };
                    const logodata = await uni.login(options)

                    const [loginErr, loginData] = logodata;
                    // console.log(loginData.code, '获取code')
                    if (loginErr) return uni.showToast({
                        title: loginErr,
                        icon: 'none'
                    }); //判断是否支持微信登录。
                    return loginData.code;
                }
                return null;
            },
            onLoad(options) {
                const scene = decodeURIComponent(options.scene)
                if (scene) {
                    let pid = scene.split("=");
                    this.pid = pid[1];
                }
                // 首先检查用户是否已经登录，登录直接跳转到首页
                let openId = getStorage('openId');
                if (openId) {
                    uni.switchTab({
                        url: `../index/index`
                    })
                }
            }
        }
    }
</script>

<style scoped>
    .logoBox {
        border: 0rpx solid red;
        height: 200rpx;
        width: 200rpx;
        border-radius: 50%;
        margin: 0 auto;
        margin-top: 200rpx;
    }

    .logoBox>img {
        height: 100%;
        width: 100%;
        border-radius: 50%;
    }

    .btnBox {
        margin-top: 100rpx;
    }

    .submitBtn {
        background: rgb(51, 150, 251) !important;
        color: #fff;
    }

    .fontBox {
        width: 90%;
        border: 0rpx solid red;
        margin: 0 auto;
        margin-top: 20rpx;
        text-align: center;
        font-size: 24rpx;
    }

    .fontBox font {
        font-size: 22rpx;
        color: #e5702e !important;
    }
</style>
